package com.iot.server.common.utils;

import com.iot.server.common.annotation.NotNullValue;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author wuzt
 * Date 2019/5/30 17:30
 * Version 1.0
 * @ClassName ValidateEntityNotEmpty
 * Description
 **/
public class ValidateEntityNotEmpty {

    /**
     * 验证传入的对象不能为空
     *
     * @param obj
     * @param skipFields 不需要验证的属性
     * @return
     */
    public static String validateEmpty(Object obj, List<String> skipFields) {
        StringBuffer bf = new StringBuffer();
        if (null != obj) {
            Class cls = obj.getClass();
            Field[] fields = cls.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                if (null != skipFields && skipFields.contains(fields[i].getName())) {
                    continue;
                }
                fields[i].setAccessible(true);
                NotNullValue notNull = fields[i].getAnnotation(NotNullValue.class);
                if (null != notNull) {
                    try {
                        Object value = fields[i].get(obj);
                        if (null == value || StringUtils.isEmpty(value.toString())) {
                            bf.append(notNull.msg());
                            break;
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            bf.append("对象不能为空");
        }
        return bf.toString();
    }
}
